/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.portal;

import com.servengine.struts.AdminServiceAction;
import com.servengine.user.Role;
import com.servengine.user.UserSessionSBean;

import java.io.IOException;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.transaction.UserTransaction;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ServicesAdminActions extends com.servengine.struts.ClientAction implements AdminServiceAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( ServicesAdminActions.class.getName() );

	public void initAction(javax.naming.Context context)
	{
		log.info(getClass().getName()+" initialized");
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			ServicesActionForm servicesForm = (ServicesActionForm)form;
			servicesForm.setServiceNames(userSession.getPortal().getServiceNames().toArray(new String[0]));
			request.setAttribute("services",portalmanager.getNonSystemServiceNames());
		  return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	protected Set<String> getServices(Set<Component> actions)
	{
	  Set<String> services = new HashSet<String>();
	  for (Component action: actions)
	    services.add(action.getServiceName());
	  return services;

	}
	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
	  UserTransaction ut = null;
		try
		{
		  ut = getUserTransaction();
		  UserSessionSBean userSession = getUserSession(request);
			Portal portal = portalmanager.getPortal(userSession.getPortalid());
		  ServicesActionForm servicesForm = (ServicesActionForm)form;
		  Collection<String> portalServiceNames = portal.getServiceNames();
			Role adminRole = usermanager.getRole(portal.getId(),"admin");//FIXME
			Role userRole = null; //Puede que el sistema no tenga role de usuario
			try
			{
				userRole = usermanager.getRole(portal.getId(),"user");//FIXME
			} catch (Throwable e)
			{
				log.error(e.getMessage(),e);
			}
			for (String serviceName: portalmanager.getNonSystemServiceNames())
			{
				if (servicesForm.getServiceNamesList().contains(serviceName) && !portalServiceNames.contains(serviceName))
					for (Component action: portalmanager.getActionsForServiceName(serviceName))
					{
						portal.getActions().add(action);
						if (action.isAdmin())
							adminRole.getActions().add(action);
					  else if (userRole!=null && !action.isGuest())
					    userRole.getActions().add(action);
					}
				if (!servicesForm.getServiceNamesList().contains(serviceName) && portalServiceNames.contains(serviceName))
				  for (Component action: portalmanager.getActionsForServiceName(serviceName))
				  {
						portal.getActions().remove(action);
						if (action.isAdmin())
							adminRole.getActions().remove(action);
						if (userRole!=null && !action.isGuest())
							userRole.getActions().remove(action);
					}
			}
			for (String systemServiceName: portalmanager.getSystemServiceNames())
			  for (Component action: portalmanager.getActionsForServiceName(systemServiceName))
			   {
					portal.getActions().add(action);
					if (action.isAdmin())
						adminRole.getActions().add(action);
					else if (userRole!=null && !action.isGuest())
						userRole.getActions().add(action);
				 }
			 usermanager.persist(adminRole);
			 if (userRole!=null)
				usermanager.persist(userRole);
			userSession.refresh(portalmanager.persist(portal));
			ut.commit();
		  logManager.log(userSession.getPortalid(),userSession.getUser().getId(),"portal","ServicesAdminActions","store",null,request.getRemoteAddr());
			return unspecified(mapping,form,request,response);
		} catch (Throwable e)
		{
			try
			{
				ut.rollback();
			} catch (Exception e2)
			{
				log.error(e.getMessage(),e2);
			}
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
/*	protected Collection<ComponentSBean> getAdminActions(PortalSBean portal, String service) throws FinderException, RemoteException
	{
		ArrayList<ComponentSBean> res = new ArrayList<ComponentSBean>();
		for (String className: portal.getActiveActionClassNames())
		{
			ComponentSBean action = getServletContextUtils().getAllActionsInContext().get(className);
			if (action.isAdmin() && action.getServiceName().equals(service))
				res.add(action);
		}
		return res;
	}
	protected Collection<ComponentSBean> getActions(PortalSBean portal, String service) throws FinderException, RemoteException
	{
		ArrayList<ComponentSBean> res = new ArrayList<ComponentSBean>();
	  for (String className: portal.getActiveActionClassNames())
	  {
		  ComponentSBean action = getServletContextUtils().getAllActionsInContext().get(className);
			if (!action.isAdmin() && action.getServiceName().equals(service))
				res.add(action);
		}
		return res;
	}*/

}
